<?php

class UserController extends Controller
{
    public $layout = '//layouts/main';
    public $defaultAction = 'manage';

    public function actionManage()
    {
        $model = new User('search');
        if (isset($_GET['User'])) {
            $model->attributes = $_GET['User'];
        }
        if (isset($_GET['searchKey'])) {
            $model->searchKey = $_GET['searchKey'];
        }
        $this->render('manage', array(
            'model' => $model,
        ));
    }

    public function actionCreate()
    {
        $model = new User('new');
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            $uncodePassword = $model->password;
            $model->pwd_salt = $model->getRandomStr();
            $model->password = md5($model->pwd_salt . $model->password);
            $model->passwordConfirm = md5($model->pwd_salt . $model->passwordConfirm);
            if ($model->save()) {
                $this->redirect(array($this->defaultAction));
            }
            $model->password = $uncodePassword;
        }
        $this->render('model', array(
            'model' => $model,
        ));
    }

    public function actionUpdate()
    {
        if (isset($_GET['id'])) {
            $model = User::model()->findByPk($_GET['id']);
            if ($model) {
                $currentPassword = $model->password;
                $model->password = '';
                if (isset($_POST['User'])) {
                    $newPassword = '';
                    $newPasswordConfirm = '';
                    $model->attributes = $_POST['User'];
                    if (($model->password == '') && ($model->passwordConfirm == '')) {
                        $model->password = $currentPassword;
                        $model->passwordConfirm = $currentPassword;
                    } else {
                        $newPassword = $model->password;
                        $newPasswordConfirm = $model->passwordConfirm;
                        $model->password = md5($model->pwd_salt . $model->password);
                        $model->passwordConfirm = md5($model->pwd_salt . $model->passwordConfirm);
                    }
                    if ($model->save()) {
                        $this->redirect(array($this->defaultAction));
                    }
                    $model->password = $newPassword;
                    $model->passwordConfirm = $newPasswordConfirm;
                }
                $this->render('model', array(
                    'model' => $model,
                ));
            } else {
                $this->redirect(array($this->defaultAction));
            }
        } else {
            $this->redirect(array($this->defaultAction));
        }
    }

    public function actionToken()
    {
        if (isset($_GET['id'])) {
            $model = User::model()->findByPk($_GET['id']);
            if ($model) {
                if (empty($model->token)) {
                    $model->generateToken();
                }
                if (empty($model->token)) {
                    Yii::app()->user->setFlash('alert-failure', 'Error!');
                } else {
                    Yii::app()->user->setFlash('alert-success', 'Token:' . $model->token);
                }
                $this->redirect(array($this->defaultAction));
            } else {
                $this->redirect(array($this->defaultAction));
            }
        } else {
            $this->redirect(array($this->defaultAction));
        }
    }

    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            $model = User::model()->findByPk($id);
            if ($model) {
                $isAdmin = Yii::app()->user->isAdmin();
                $loginUserId = Yii::app()->user->getState('user_id');
                if ($isAdmin) {
                    if ($model->isAdmin()) {
                        echo 'Permission Deny!';
                    } else {
                        if ($model->delete()) {
                            echo 'Success';
                        } else {
                            echo 'Error:DB Delete Failure!';
                        }
                    }
                } else {
                    echo 'Permission Deny!';
                }
            } else {
                echo 'Error:Object is not Exist!';
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionAuthsso()
    {
        try{
            $redirect = '/' . Yii::app()->defaultController;
            $flash = 'login success';
            //auth sso
            $sso = PersonApiSso::auth($_GET['ticket']);
            if ($sso&&isset($sso['name'])&&($ssoName=$sso['name'])) {
                $userSso = UserSso::model()->findByAttributes(['sso_name' => $ssoName]);
                if (($ssoName) && (empty($userSso) || empty($user = $userSso->user))) {
                    //can't find this people
                    //create new user for this sso user
                    $passWord = md5(time() . $ssoName);
                    $user = User::build('msgg_' . $ssoName, $passWord, array('cnname' => $sso['cname']));
                    if ($user && $user->save()) {
                        $userSso = UserSso::build($user->id, $ssoName);
                        if (!$userSso || !$userSso->save()) {
                            throw  new Exception('usersso save failed', 1);
                        }
                        $redirect = '/account/profile';
                        $flash .= ' 请及时修改密码!!';
                    } else {
                        throw  new Exception('user save failed', 1);

                    }
                }
                $identity = new UserIdentity($user->name, $user->password);
                $identity->authenticate();
                // 验证成功
                if ($identity->errorCode === UserIdentity::ERROR_NONE) {
                    //设置缓存
                    $duration = 3600 * 24 * 7; // 14 days
                    Yii::app()->user->login($identity, $duration);
                    //设置login时间
                    $user->last_login_time = date("Y-m-d H:i:s", time());
                    $user->save();
                    Yii::app()->user->setFlash('alert-success', $flash);
                }
            }
            else{
                throw  new Exception('empty ssoname', 1);
            }
        }catch(Exception $e){
            if(SYS_ENV=='DEV')
            {
                throw  $e;
            }
            Yii::log($e->getTraceAsString(), CLogger::LEVEL_ERROR, __METHOD__);
        }

        $this->redirect(array($redirect,));
    }

    public function colRevise($data, $row, $c)
    {
        $name = $c->name;
        switch ($name) {
            case 'rid':
                $role = Role::model()->findByPk($data->$name);
                if ($role) {
                    return $role->name;
                } else {
                    return 'NoExist';
                }
                break;
            case 'status':
                $map = User::getOptions($name);
                return isset($map[$data->$name]) ? $map[$data->$name] : '-';
                break;
            default:
                return $data->$name;
        }
    }

    // Uncomment the following methods and override them if needed
    /*
    public function filters()
    {
        // return the filter configuration for this controller, e.g.:
        return array(
            'inlineFilterName',
            array(
                'class'=>'path.to.FilterClass',
                'propertyName'=>'propertyValue',
            ),
        );
    }

    public function actions()
    {
        // return external action classes, e.g.:
        return array(
            'action1'=>'path.to.ActionClass',
            'action2'=>array(
                'class'=>'path.to.AnotherActionClass',
                'propertyName'=>'propertyValue',
            ),
        );
    }
    */
}